package org.njo.webapp.root.log4j;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.jdbc.JDBCAppender;
import org.njo.webapp.root.utility.SystemContext;

/**
 * log4j 使用数据库连接池,向数据库中输出log.
 */
public class JDBCPoolAppender extends JDBCAppender {

    /**
     * Override this to return the connection to a pool, or to clean up the
     * resource.
     *
     * The default behavior holds a single connection open until the appender
     * is closed (typically when garbage collected).
     */
    protected void closeConnection(Connection con) {
        try {
            SystemContext.closeConnection(con);
        } catch (SQLException e) {
            
        }
    }

    /**
     * Override 此函数来利用连接池返回一个Connetion对象
     *
     */
    protected Connection getConnection() throws SQLException {
        return SystemContext.openConnection();
    }

    public JDBCPoolAppender() {
        super();
    }

    /**
     * 因为从数据连接池中取得的connection不是自动提交的,
     * 覆盖父类,在执行SQL后提交.
     *
     * Override this to provide an alertnate method of getting
     * connections (such as caching).　One method to fix this is to open
     * connections at the start of flushBuffer() and close them at the
     * end.　I use a connection pool outside of JDBCAppender which is
     * accessed in an override of this method.
     */
    protected void execute(String sql) throws SQLException {
        Connection connnection = null;
        Statement stmt = null;
        try {
            connnection = getConnection();
            stmt = connnection.createStatement();
            stmt.executeUpdate(sql);
            stmt.close();
            connnection.commit();
        } catch (SQLException e) {
            throw e;
        } finally {
            closeConnection(connnection);
        }
    }

}
